#include "dlgcurve.h"
#include "ui_dlgcurve.h"
#include <QDebug>
#include <QDate>

DlgCurve::DlgCurve(QWidget *parent,CSql* sql,QCustomPlot* plot) :
    QDialog(parent),
    ui(new Ui::DlgCurve),
    m_Sql(sql),
    m_plot(plot)
{
    ui->setupUi(this);

    m_plot->legend->setVisible(true);

    //myPlot->setFixedSize(480,300);
    m_plot->setFixedSize(600,480);
    //blue line
    m_plot->addGraph();
    m_plot->graph(0)->setPen(QPen(Qt::blue));
    m_plot->graph(0)->setName("Gap");
    m_plot->addGraph();
    m_plot->graph(1)->setPen(QPen(Qt::green));
    m_plot->graph(1)->setName("Flush");
    //xAxis
    m_plot->axisRect()->setupFullAxesBox();
    m_plot->xAxis->setRange(0, 10);
    m_plot->yAxis->setRange(0, 15);
    QSharedPointer<QCPAxisTickerFixed> fixedTicker(new QCPAxisTickerFixed);
    m_plot->xAxis->setTicker(fixedTicker);
    m_plot->yAxis->setTicker(fixedTicker);
    fixedTicker->setTickStep(1.0); // tick step shall be 1.0
    fixedTicker->setScaleStrategy(QCPAxisTickerFixed::ssNone);

    //myPlot->xAxis->setRange(1, 10, Qt::AlignRight);
    //myPlot->yAxis->setRange(1, 15, Qt::AlignRight);
    m_plot->xAxis->setLabel("单个测量点(次)");
    m_plot->yAxis->setLabel("毫米(mm)");



    ui->dateEdit->setDate(QDate::currentDate());
    connect(ui->pBQuery, SIGNAL(clicked()), this, SLOT(myQuery()));


    connect(ui->cBoxPrj,SIGNAL(currentIndexChanged(int)),this,SLOT(onCurrentIndexChanged(int)));
    //connect(ui->cBoxM,SIGNAL(currentIndexChanged(int)),this,SLOT(onLayerCurrentIndexChanged(int)));

    //connect(m_plot, SIGNAL(mousePress(QMouseEvent *)), this, SLOT(slot_SameTimeMousePressEvent4Plot(QMouseEvent*)));
    connect(m_plot, SIGNAL(mouseMove(QMouseEvent *)), this, SLOT(slot_SameTimeMousePressEvent4Plot(QMouseEvent*)));

    showPrj();
    showPara(0);

}

DlgCurve::~DlgCurve()
{
    delete ui;
}
void DlgCurve::showPrj()
{
    QStringList items;
    NODE nd;
    NODE rds;
    std::string value;
    items << tr("Spring") << tr("Summer") << tr("Fall") << tr("Winter");
    items.clear();
    RECORDSET rd = m_Sql->RecordSet("select * from fsapp");
    ui->cBoxPrj->clear();

    if(rd.size()>0){
        for(RECORDSET::iterator it = rd.begin();it!=rd.end();it++){
        //for(int i = 0;i<rd.size();i++){
            nd =  *it;
            value = nd["value"];
            items << QString::fromLocal8Bit(value.c_str());
            //rds[value] = nd["para"];
            //qDebug() << QString::fromLocal8Bit(value.c_str());
        }
    }
    ui->cBoxPrj->addItems(items);
}
void DlgCurve::showPara(int idx)
{
    QStringList items;
    NODE nd;
    NODE rds;
    //int idx1,idx2,row=0;
    //idx1 = ui->cBoxPrj->currentIndex();


    std::string value;
    QString sql;
    sql = QString("select id from fspoint where fsapp = '%1'").arg(ui->cBoxPrj->itemText(idx));
    RECORDSET rd = m_Sql->RecordSet(sql.toStdString());
    ui->cBoxM->clear();


    //QRegExp regexp_DDD("^(\\d+)(\\.){0,1}(\\d+)$");
    QRegExp regexp_DDD("^(\\d+\\.{1}\\d+)$");
    QRegExp regexp_0To255("^(0|[1-9]{1,2}|[1]\\d{0,2}|2[0-4]\\d|255)$");
    QRegExp regexp_0To128("^(0|[1-9]{1,2}|[1][0-2][0-8])$");

    if(rd.size()>0){

        for(RECORDSET::iterator it = rd.begin();it!=rd.end();it++){
        //for(int i = 0;i<rd.size();i++){
            nd =  *it;
            value = nd["id"];
            items << QString::fromLocal8Bit(value.c_str());
        }
        ui->cBoxM->addItems(items);
    }


}

void DlgCurve::onCurrentIndexChanged(int idx)
{
    //qDebug()<< __FUNCTION__ << idx;
    showPara(idx);
    //showPara();
}
void DlgCurve::myQuery()
{
    NODE nd;
    std::string value;
    QVector<float> qvGap,qvFlush;
    float a;
    QString sql,app,point,dt;
    QDate dd = ui->dateEdit->date();
    app = ui->cBoxPrj->itemText(ui->cBoxPrj->currentIndex());
    point = ui->cBoxM->itemText(ui->cBoxM->currentIndex());

    m_plot->graph(0)->data().data()->clear();
    m_plot->graph(1)->data().data()->clear();
    m_plot->replot();

    dt = dt.asprintf("%d%02d%02d",dd.year(),dd.month(),dd.day());
    sql = QString("select gap,flush from fsdata where fsapp = '%1' and point = '%2' and dt='%3' order by dt,tim").arg(app,point,dt);
    qDebug()<<sql;
    RECORDSET rd = m_Sql->RecordSet(sql.toStdString());
    if(rd.size()>0){
        QSharedPointer< QCPGraphDataContainer > dataContainerA,dataContainerB;
        dataContainerA = m_plot->graph(0)->data();
        dataContainerB = m_plot->graph(1)->data();
        QVector<QCPGraphData> mDataA,mDataB; //warning: it's a local var
        QCPGraphData newPointA,newPointB;

        int i = 0;
        for(RECORDSET::iterator it = rd.begin();it!=rd.end();it++){
        //for(int i = 0;i<rd.size();i++){
            nd =  *it;
            value = nd["gap"];
            a = qAbs(atof(value.c_str()));
            qvGap.push_back(a);

            newPointA.key = i;
            newPointA.value = a;
            mDataA.append(newPointA);

            value = nd["flush"];
            a = qAbs(atof(value.c_str()));
            qvFlush.push_back(a);

            newPointB.key = i;
            newPointB.value = a;
            mDataB.append(newPointB);
            i++;
        }
        dataContainerA->set(mDataA,true); //if the data has been sorted, set true
        dataContainerB->set(mDataB,true); //if the data has been sorted, set true

        qDebug() << dataContainerA->at(0)->mainValue();

        m_plot->xAxis->setLabel(QString("测量点(%1)(次)").arg(point));
        m_plot->xAxis->setRange(0, rd.size());
        m_plot->replot();

    }
}


/**
 *  获取选中点的数值
 * @brief CADBCompareView::slot_SameTimeMousePressEvent4Plot
 * @param e
 */
void DlgCurve::slot_SameTimeMousePressEvent4Plot(QMouseEvent *e)
{
    QCPGraph *graph = qobject_cast<QCPGraph*>(m_plot->plottableAt(e->pos(),true));

    int x = (int)m_plot->xAxis->pixelToCoord(e->pos().x());
    //qDebug() << x;
    QPointF pressPos(0,0);//跟踪鼠标点击事件点击位置
    QRect rect(0,0,1,1);
    double key = 0,value = 0;
    //if(graph)
    {
        if(m_sameTimeTracer == NULL)
        {
            m_sameTimeTracer = new QCPItemTracer(m_plot);
            m_sameTimeTracer->setParent(m_plot);
            m_sameTimeTracer->setPen(QColor(255,255,255));
            m_sameTimeTracer->setBrush(QBrush(QColor(255,0,0),Qt::SolidPattern));
            m_sameTimeTracer->setStyle(QCPItemTracer::tsCircle);
            m_sameTimeTracer->setSize(10);
            m_sameTimeTracer->setVisible(false);
        }
        if(m_sameTimeTextTip == NULL)
        {
            m_sameTimeTextTip = new QCPItemText(m_plot);
            m_sameTimeTextTip->setPositionAlignment(Qt::AlignTop|Qt::AlignHCenter);
            m_sameTimeTextTip->position->setType(QCPItemPosition::ptAbsolute);
            QFont font;
            font.setPixelSize(14);

            m_sameTimeTextTip->setFont(font); // make font a bit larger
            m_sameTimeTextTip->setPen(QPen(Qt::blue)); // show black border around text
            m_sameTimeTextTip->setBrush(Qt::white);
            m_sameTimeTextTip->setPadding(QMargins(3, 4, 3, 4));
            m_sameTimeTextTip->setColor(Qt::blue);

            m_sameTimeTextTip->setVisible(false);

            m_sameTimeTextTipB = new QCPItemText(m_plot);
            m_sameTimeTextTipB->setPositionAlignment(Qt::AlignTop|Qt::AlignHCenter);
            m_sameTimeTextTipB->position->setType(QCPItemPosition::ptAbsolute);
            QFont fontB;
            fontB.setPixelSize(14);
            m_sameTimeTextTipB->setFont(font); // make font a bit larger
            m_sameTimeTextTipB->setPen(QPen(Qt::green)); // show black border around text
            m_sameTimeTextTipB->setBrush(Qt::white);
            m_sameTimeTextTipB->setPadding(QMargins(3, 4, 3, 4));
            m_sameTimeTextTipB->setColor(Qt::green);

            m_sameTimeTextTipB->setVisible(false);

        }


        double posKeyA=0.0,posKeyB=0.0;


        QSharedPointer< QCPGraphDataContainer > dataContainerA,dataContainerB;
        dataContainerA = m_plot->graph(0)->data();
        dataContainerB = m_plot->graph(1)->data();

        posKeyA = dataContainerA->at(x)->mainValue();
        posKeyB = dataContainerB->at(x)->mainValue();

        pressPos.setX(posKeyA);
        pressPos.setY(posKeyA>posKeyB ? posKeyA:posKeyB);

        //qDebug() << posKeyA << dataContainerA->size();

        //if(pressPos.x()!=0 && pressPos.y()!=0)
        if(dataContainerA->size()>0)
        {
            //m_sameTimeTextTip->setText(tr("<font style = 'font-size:14px; color:red;'> Gap:%1 </font>").arg(QString::number(posKeyB))
            //+ tr("<font style = 'font-family:MicrosoftYaHei; font-size:20px; color:#F13232;'>\nFlush:%2</font>").arg(QString::number(posKeyA)));


            m_sameTimeTextTip->setText("  Gap: "+QString::number(posKeyA,'f',3));
            m_sameTimeTextTip->position->setCoords(e->pos().x()+45,e->pos().y()-35);
            m_sameTimeTextTip->setVisible(true);
            m_sameTimeTextTipB->setText("Flush: "+QString::number(posKeyB,'f',3));
            m_sameTimeTextTipB->position->setCoords(e->pos().x()+45,e->pos().y()-55);
            m_sameTimeTextTipB->setVisible(true);

            m_plot->replot();
        }else
        {
            if(m_sameTimeTextTip != NULL)
            {
                m_sameTimeTextTip->setVisible(false);
                m_sameTimeTextTipB->setVisible(false);
                m_plot->replot();
            }
        }


    }
}
